import { reactive } from 'vue'
import http from './http'

// 存储所有字典数据
const DICT_MAP = new Map()
// key请求锁，防止重复请求
const LOCK_SET = new Set()

/**
 * 字典请求
 * @param key 字典KEY
 * @param container 字典数据存放容器
 */
function requestDict(key, container) {
    if (LOCK_SET.has(key)) {
        return
    }
    LOCK_SET.add(key)
    http.getDictDataByType({
        jointUrl: '/' + key
    }).then(res => {
        if (res.data?.length) {
            res.data.forEach(v => {
                container[v.dictLabel] = v.dictValue
                container.push({
                    label: v.dictLabel,
                    value: v.dictValue,
                    tagType: v.listClass,
                    className: v.cssClass
                })
            })
        }
    }).catch(err => {
        console.error(`字典加载失败：${ key }`)
    })
}

/**
 * 字典数据代理对象
 */
const Dict = new Proxy(Object.create(null), {
    get(target, key, receiver) {
        // 防止vue模板中使用Dict.xxx加载字典数据
        if (key === '__v_isRef') return []
        let value = DICT_MAP.get(key)
        if (!value) {
            value = reactive([])
            value.isHaveIn = (value, ...label) => {
                for (const labelElement of label)
                    if (value[labelElement] === value) return true
                return false
            }
            value.isNotHaveIn = (value, ...label) => {
                for (const labelElement of label)
                    if (value[labelElement] === value) return false
                return true
            }
            DICT_MAP.set(key, value)
            requestDict(key, value)
        }
        return value
    },
    set(target, key, value) {
        return true
    }
})

export default Dict
